package com.mytx.sso.controller;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mytx.common.config.MytxConfig;
import com.mytx.common.constant.Constant;
import com.mytx.common.pojo.CommonResult;
import com.mytx.common.pojo.RedisLock;
import com.mytx.common.utils.EntityUtils;
import com.mytx.common.utils.IDUtils;
import com.mytx.mapper.*;
import com.mytx.pojo.*;
import com.mytx.sso.service.ConsumerSearchService;
import com.mytx.sso.utils.PayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

@SuppressWarnings({"SpringJavaInjectionPointsAutowiringInspection", "Duplicates"})
@RestController
public class DonationController {
    private static Logger logger = LoggerFactory.getLogger(DonationController.class);

    @Autowired
    DonationMapper donationMapper;
    @Autowired
    ForwardMapper forwardMapper;
    @Autowired
    TopicMapper topicMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private ConsumerSearchService searchService;

    @Autowired
    MyFileMapper myFileMapper;

    @Autowired
    private HttpServletRequest request;

    /**
     * 捐赠
     *
     * @return
     */
    @Transactional
    @RequestMapping(value = "/donationToTopic", method = RequestMethod.POST)
    public CommonResult donationToTopic(@RequestBody JSONObject body) {
        Donation donation = body.getJSONObject("donation").toJavaObject(Donation.class);

        String uId = request.getHeader("uId");
        //  CommonResult validatePasswordResult = validatePassword(body, donation, uId);
        User user = getUser(uId);
        BigDecimal amount = donation.getAmount();
        String payPassword = body.getString("payPassword");

        donation.setmId(uId);
        Date currentDate = new Date();
        RedisLock lock = new RedisLock(redisTemplate, Constant.USER_SESSION_LOCK + uId);
        try {
            if (!lock.lock()) {
                logger.error("donationToTopic:捐款出错，获取锁失败了" + uId, donation);
                return CommonResult.build(Constant.GET_LOCK_FAIL, "捐款出错，获取锁失败了");
            }
            CommonResult commonResult = PayUtils.payPrepare(payPassword, amount, user);
            if (commonResult != null) return commonResult;
            String topicId = donation.getoId();
            Topic topic = topicMapper.selectByPrimaryKey(topicId);
            if ((topic.getStatus() == Constant.TOPIC_STATUS_REWARD_COMPLETE)||(topic.getStatus()==Constant.TOPIC_STATUS_REWARD_CANCEL)) {
                //悬赏任务已经结束了
                return CommonResult.build(Constant.TOPIC_STATUS_ERROR, "悬赏任务已经结束了");
            }

            Donation historyDonation = donationMapper.selectMyValidHistoryDonation(uId, topicId, Constant.DONATION_TYPE_TO_TOPIC);
            String donationId;
            BigDecimal totalDonationAmount = null;
            Topic updateTopic = null;

            if (historyDonation == null) {
                donationId = IDUtils.genOrderItemId();

                donation.setId(donationId);
                donation.setType(Constant.DONATION_TYPE_TO_TOPIC);
                donation.setStatus(Constant.DONATION_STATUS_COULD_REVOKE);
                donation.setCreated(currentDate);
                donationMapper.insertSelective(donation);//持久化捐赠信息到mysql
                updateTopic = topicMapper.incrementReceivedDonationData_v1(amount, topicId, currentDate);
            } else {
                donationId = historyDonation.getId();
                totalDonationAmount = donationMapper.incrementDonationAmount(donationId, amount, currentDate);
                historyDonation.setUpdated(currentDate);
                historyDonation.setAmount(totalDonationAmount);
                updateTopic = topicMapper.incrementReceivedDonationData(amount, topicId, currentDate);

            }


            //更新mysql中用户余额、捐赠总额
            User donor = userMapper.incrementDonationAmount(amount, uId, currentDate);
            //对捐赠用户余额做减少操作，持久化到mysql,并更新缓存，
            redisTemplate.opsForHash().putAll(Constant.USER_SESSION + uId, EntityUtils.objectToMap_v1(donor));

            //更新主题在ES中的捐赠余额，这样从ES 搜出来的主题数据就携带 捐赠余额了
            updateTopic.setId(topicId);
            searchService.update(updateTopic);
            // logger.info("donationToTopic:uId:{}   amount:{}", uId, amount);
            if (totalDonationAmount == null) {
                logger.info("donationToTopic:新捐赠，用户余额减少 uId:{}, amount:{},balance:{},donationAmount:{},donationId:{},",
                        uId, amount, donor.getBalance(), donor.getDonationAmount(), donationId);
                logger.info("updateAdvertisement:主题收新捐赠， uId:{},topicId:{},  donationId:{},捐赠金额：{},捐赠前捐赠余额：{}，捐赠前捐赠总额：{},捐赠前捐赠笔数：{}，捐赠后捐赠余额：{}，捐赠后捐赠总额：{}，捐赠后捐赠笔数：{}",
                        uId, topicId, donationId, amount, topic.getDonationBalance(), topic.getDonationReceived(), topic.getDonationSize(), updateTopic.getDonationBalance(), updateTopic.getDonationReceived(), updateTopic.getDonationSize());
            } else {
                logger.info("donationToTopic:追加捐赠，用户余额减少 uId:{},amount:{},balance:{},donationAmount:{},donationId:{},捐赠前捐赠金额：{}，捐赠后捐赠金额 :{}",
                        uId, amount, donor.getBalance(), donor.getDonationAmount(), donationId, historyDonation.getAmount(), totalDonationAmount);
                logger.info("updateAdvertisement:主题收追加捐赠， uId:{},topicId:{},  donationId:{},捐赠金额：{},捐赠前捐赠余额：{}，捐赠前捐赠总额：{},捐赠前捐赠笔数：{}，捐赠后捐赠余额：{}，捐赠后捐赠总额：{}，捐赠后捐赠笔数：{}",
                        uId, topicId, donationId, amount, topic.getDonationBalance(), topic.getDonationReceived(), topic.getDonationSize(), updateTopic.getDonationBalance(), updateTopic.getDonationReceived(), updateTopic.getDonationSize());

            }


            JSONObject response = new JSONObject();
            response.put("balance", donor.getBalance());
            response.put("donationAmount", donor.getDonationAmount());
            if (historyDonation == null) {
                response.put("donationId", donation.getId());
            } else {
                response.put("historyDonation", historyDonation);
            }
            return CommonResult.ok(response);

        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("捐款出错：未知错误", e);
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            lock.unlock();
        }
    }

    /**
     * 拆回捐赠
     *
     * @param donation
     * @return
     */
    @Transactional
    @PostMapping("/revokeDonation")
    public CommonResult revokeDonation(@RequestBody Donation donation) {

        String uId = request.getHeader("uId");
        String donationId = donation.getId();
        Donation tableDonation = donationMapper.selectByPrimaryKey(donationId);
        //判断当前操作的用户是否为自己
        if(!StringUtils.equals(tableDonation.getmId(),uId)){
            return CommonResult.build(Constant.PARAMETER_INVALID,"你不是本人,不可拆回");
        }
        if (tableDonation.getStatus()==Constant.DONATION_STATUS_ALREADY_REVOKE){
            logger.error("revokeDonation:反复拆回同一笔捐赠，uId:{},donationId:{}",uId,donationId);
            return CommonResult.build(Constant.DONATION_STATUS_ERROR,"该笔捐赠已经拆回");
        }

        RedisLock lock = new RedisLock(redisTemplate, Constant.USER_SESSION_LOCK + uId);
        try {
            if (!lock.lock()) {
                logger.error("捐款出错，获取锁失败了" + uId, donation);
                return CommonResult.build(Constant.GET_LOCK_FAIL, "捐款出错，获取锁失败了");
            }
        //更新捐赠的状态为 已经拆回状态
        Date currentDate = new Date();
        donation.setStatus(Constant.DONATION_STATUS_ALREADY_REVOKE);
        donation.setUpdated(currentDate);
        donationMapper.updateByPrimaryKeySelective(donation);
        //把捐赠的金额返回给用户，同时减去用户的捐款总额
        BigDecimal amount = donation.getAmount();
        User user = userMapper.incrementBalanceAndReduceDonationAmount(uId, amount);
        String topicId = donation.getoId();
        //减少主题收到的捐赠总额和余额
        Topic topic = topicMapper.reduceDonationBalanceAndDonationReceived(amount, topicId, currentDate);
        //把变更了捐赠余额和捐赠总额的主题信息更新到ES
        searchService.update(topic);
        redisTemplate.opsForHash().putAll(Constant.USER_SESSION + uId,  EntityUtils.objectToMap_v1(user));

        logger.info("revokeDonation:用户余额增加，捐赠总额减少，uId:{},amount:{},donationId:{}，balance：{},donationAmount:{}", uId, amount, donationId,user.getBalance(),user.getDonationAmount());
        logger.info("revokeDonation:主题捐赠余额、总额减少，topicId:{},amount:{},donationId:{},donationBalance:{},donationReceived:{},donationSize:{}", topicId, amount, donationId,topic.getDonationBalance(),topic.getDonationReceived(),topic.getDonationSize());

        return CommonResult.ok(user.getBalance());
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("revokeDonation：拆回捐赠出错：未知错误", e);
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    @PostMapping(value = "/donationSupportUs")
    public CommonResult donationSupportUs(@RequestBody JSONObject body) {

        Donation donation = body.getJSONObject("donation").toJavaObject(Donation.class);
        String uId = request.getHeader("uId");
        donation.setmId(uId);
        donation.settId(MytxConfig.serviceUserId);
        User serviceUser = getServiceUser();
        BigDecimal amount = donation.getAmount();
        String payPassword = body.getString("payPassword");
        User user = getUser(uId);

        RedisLock lock = new RedisLock(redisTemplate, Constant.USER_SESSION_LOCK + uId);
        try {
            if (!lock.lock()) {
                logger.error("捐款出错，获取锁失败了" + uId, donation);
                return CommonResult.build(Constant.GET_LOCK_FAIL, "捐款出错，获取锁失败了");
            }

            CommonResult commonResult = PayUtils.payPrepare(payPassword, amount, user);
            if (commonResult != null) {
                return commonResult;
            }
            Date currentDate = new Date();
            BigDecimal totalAmount = null;
            String donationId;
            Donation historyDonation = donationMapper.selectMyHistoryDonationToPerson(uId, MytxConfig.serviceUserId);

            if (historyDonation == null) {

                donationId = IDUtils.genOrderItemId();
                donation.setId(donationId);
                donation.setType(Constant.DONATION_TYPE_TO_PERSON);
                donation.setStatus(Constant.DONATION_STATUS_COULD_NOT_REVOKE);
                donation.settId(MytxConfig.serviceUserId);
                donation.setCreated(currentDate);
                donationMapper.insertSelective(donation);//持久化捐赠信息到mysql
            } else {
                donationId = historyDonation.getId();
                totalAmount = donationMapper.incrementDonationAmount(donationId, amount, currentDate);
                historyDonation.setUpdated(currentDate);
                historyDonation.setAmount(totalAmount);
            }
            //更新mysql中捐赠人余额、捐赠总额
            User donor = userMapper.incrementDonationAmount(amount, uId, currentDate);
            //更新mysql中受赠赠人余额、受赠总额
            User receiver = userMapper.incrementReceivedDonationAmount(amount, MytxConfig.serviceUserId, currentDate);

            //更新捐款用户的缓存，
            redisTemplate.opsForHash().putAll(Constant.USER_SESSION + uId, EntityUtils.objectToMap_v1(donor));

            //先判断redis 中是否有 受款人的信息缓存，如果有就更新
            if (redisTemplate.hasKey(Constant.USER_SESSION + donation.gettId())) {
                redisTemplate.opsForHash().putAll(Constant.USER_SESSION + MytxConfig.serviceUserId, EntityUtils.objectToMap_v1(receiver));
            }

            logger.info("donationSupportUs:捐赠 用户余额减少，捐赠总额增加，uId:{},amount:{},balance:{},donationAmount:{},donationId:{}", uId, amount, donor.getBalance(), donor.getDonationAmount(), donationId);
            logger.info("donationSupportUs:收到捐赠 用户余额增加，收到捐赠总额增加，uId:{},amount:{},balance:{},donationReceived:{},donationId:{}",
                    MytxConfig.serviceUserId, amount, receiver.getBalance(), receiver.getDonationReceived(), donationId);
            if (totalAmount != null) {
                logger.info("donationSupportUs:用户:{}对:{}二次捐赠，当前捐赠金额:{},历史捐赠金额：{}，捐赠后金额：{},donationId:{}",
                        uId, MytxConfig.serviceUserId, amount, historyDonation.getAmount(), totalAmount, donationId);
            }
            JSONObject response = new JSONObject();
            response.put("balance", donor.getBalance());
            response.put("donation_amount", donor.getDonationAmount());
            if (historyDonation == null) {
                response.put("donationId", donationId);
            } else {
                response.put("historyDonation", historyDonation);
            }
            if (serviceUser != null) {
                response.put("serviceUser", serviceUser);
            }
            return CommonResult.ok(response);

        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("捐款出错：未知错误", e);
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            lock.unlock();
        }
    }

    @Transactional
    @PostMapping(value = "/donationToPerson")
    public CommonResult donationToPerson(@RequestBody JSONObject body) {

        String uId = request.getHeader("uId");
        Donation donation = body.getJSONObject("donation").toJavaObject(Donation.class);
        BigDecimal amount = donation.getAmount();
        String payPassword = body.getString("payPassword");
        logger.info("donationToPerson:uId:{},amount:{}", uId, amount);
        User user = getUser(uId);
        donation.setmId(uId);
        RedisLock lock = new RedisLock(redisTemplate, Constant.USER_SESSION_LOCK + uId);
        try {
            if (!lock.lock()) {
                logger.error("捐款出错，获取锁失败了" + uId, donation);
                return CommonResult.build(Constant.GET_LOCK_FAIL, "捐款出错，获取锁失败了");
            }
            CommonResult commonResult = PayUtils.payPrepare(payPassword, amount, user);
            if (commonResult != null) return commonResult;
            Date currentDate = new Date();
            //追加捐赠后的金额
            BigDecimal totalAmount = null;
            String donationId;
            String targetUid = donation.gettId();
            Donation historyDonation = donationMapper.selectMyHistoryDonationToPerson(uId, targetUid);
            if (historyDonation == null) {
                donationId = IDUtils.genOrderItemId();
                donation.setId(donationId);
                donation.setType(Constant.DONATION_TYPE_TO_PERSON);
                donation.setStatus(Constant.DONATION_STATUS_COULD_NOT_REVOKE);
                donation.setCreated(currentDate);
                donationMapper.insertSelective(donation);//持久化捐赠信息到mysql
            } else {
                donationId = historyDonation.getId();
                totalAmount = donationMapper.incrementDonationAmount(donationId, amount, currentDate);
                historyDonation.setUpdated(currentDate);
                historyDonation.setAmount(totalAmount);
            }
            //更新mysql中捐赠人余额、捐赠总额
            User donor = userMapper.incrementDonationAmount(amount, uId, currentDate);
            //更新mysql中受赠人余额、受赠总额
            User receiver = userMapper.incrementReceivedDonationAmount(amount, targetUid, currentDate);

            //增加转发 中的捐赠金额

            String forwardId = donation.getfId();
            BigDecimal totalDonationAmount = forwardMapper.incrementDonationAmount(forwardId, amount, currentDate);

            //更新捐款用户缓存
            redisTemplate.opsForHash().putAll(Constant.USER_SESSION + uId, EntityUtils.objectToMap_v1(donor));
            //先判断redis 中是否有 受款人的信息缓存，如果有就更新
            if (redisTemplate.hasKey(Constant.USER_SESSION + targetUid)) {
                redisTemplate.opsForHash().putAll(Constant.USER_SESSION + targetUid, EntityUtils.objectToMap_v1(receiver));
            }

            JSONObject info = new JSONObject();
            info.put("uId", targetUid);
            donation.setTargetUser(getUser(uId));//我捐赠人的信息放进donation，推送给受赠人
            info.put("donation", donation);
            redisTemplate.convertAndSend(Constant.NOTIFY_PERSON_RECEIVED_DONATION, info);
            logger.info("donationToPerson:捐赠 用户余额减少，捐赠总额增加，uId:{},amount:{},balance:{},donationAmount:{},donationId:{}", uId, amount, donor.getBalance(), donor.getDonationAmount(), donationId);
            logger.info("donationToPerson:收到捐赠 用户余额增加，收到捐赠总额增加，uId:{},amount:{},balance:{},donationReceived:{},donationId:{}",
                    MytxConfig.serviceUserId, amount, receiver.getBalance(), receiver.getDonationReceived(), donationId);
            if (totalAmount != null) {
                logger.info("donationToPerson:用户:{}对:{}二次捐赠，当前捐赠金额:{},历史捐赠金额：{}，捐赠后金额：{},donationId:{}",
                        uId, MytxConfig.serviceUserId, amount, historyDonation.getAmount(), totalAmount, donationId);
            }
            logger.info("donationToPerson:捐赠给个人，转发中的捐赠金额增加 ，forwardId:{},donationId:{} amount:{},totalDonationAmount：{}", forwardId, donationId, amount, totalDonationAmount);
            JSONObject response = new JSONObject();
            response.put("balance", donor.getBalance());
            response.put("donation_amount", donor.getDonationAmount());
            if (historyDonation == null) {
                response.put("donationId", donation.getId());
            } else {
                response.put("historyDonation", historyDonation);
            }
            return CommonResult.ok(response);

        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.error("捐款出错：未知错误", e);
            return CommonResult.build(Constant.UNKNOWN_ERROR, "未知错误");
        } finally {
            lock.unlock();
        }

    }


    /**
     * 查询个人捐赠记录
     *
     * @return
     */
    @PostMapping("/querySentDonations")
    public CommonResult querySentDonations(@RequestBody JSONObject body) {
        String uId = request.getHeader("uId");
        logger.info("查询捐赠记录：{}", uId);
        int page = 1;
        int size = 10;
        if (body.containsKey("page")) {
            page = (int) body.get("page");
        }
        if (body.containsKey("size")) {
            size = (int) body.get("size");
        }
        if (body.containsKey("uId")) {
            uId = body.getString("uId");//body中携带了uId,说明是查询别人的捐赠记录
        }
        PageHelper.startPage(page, size);
        List<Donation> donations = donationMapper.querySentDonations(uId);
        PageInfo pageInfo = new PageInfo<>(donations);
        for (Donation donation : donations) {
            Boolean member = redisTemplate.opsForSet().isMember("DONATION_PRAISE_RECORD:" + donation.getId(), uId);
            donation.setHasPraise(member);
            Object praiseSize = redisTemplate.opsForValue().get("DONATION_PRAISE_SIZE:" + donation.getId());
            if (praiseSize != null) {
                donation.setPraiseSize((Integer) praiseSize);
            }
        }
        return CommonResult.ok(pageInfo);
    }


    /**
     * 查询个人收到的 捐赠记录
     *
     * @return
     */
    @PostMapping("/queryReceivedDonations")
    public CommonResult queryReceivedDonations(@RequestBody JSONObject body) {
        String uId = request.getHeader("uId");
        logger.info("queryReceivedDonations:" + uId);
        int page = 1;
        int size = 10;
        if (body.containsKey("page")) {
            page = (int) body.get("page");
        }
        if (body.containsKey("size")) {
            size = (int) body.get("size");
        }
        PageHelper.startPage(page, size);
        List<Donation> donations = donationMapper.queryReceivedDonations_V2(uId);
        PageInfo pageInfo = new PageInfo<>(donations);
        for (Donation donation : donations) {
            Boolean member = redisTemplate.opsForSet().isMember("DONATION_PRAISE_RECORD:" + donation.getId(), uId);
            donation.setHasPraise(member);
            Object praiseSize = redisTemplate.opsForValue().get("DONATION_PRAISE_SIZE:" + donation.getId());
            if (praiseSize != null) {
                donation.setPraiseSize((Integer) praiseSize);
            }
        }
        return CommonResult.ok(pageInfo);
    }

    /**
     * 查询 系统 收到的 捐赠记录
     * <p>
     * "支持我们" 形成的捐赠
     *
     * @return
     */
    @PostMapping("/queryServiceDonations")
    public CommonResult queryServiceDonations(@RequestBody JSONObject body) {
        String uId = request.getHeader("uId");
        // logger.info("queryServiceDonations:查询系统捐赠记录");
        int page = 1;
        int size = 10;
        if (body.containsKey("page")) {
            page = (int) body.get("page");
        }
        if (body.containsKey("size")) {
            size = (int) body.get("size");
        }
        JSONObject result = new JSONObject();
        //获取第一页数据（第一次获取数据）的时候，才去获取总金额
        if (page == 1) {
            //Double totalAmount = donationMapper.getReceivedTotalAmount(serviceUserId);//查询mysql方法

            //查询Redis 方法
            Object amount = redisTemplate.opsForHash().get(Constant.USER_SESSION + MytxConfig.serviceUserId, Constant.DONATION_RECEIVED);
            BigDecimal totalAmount;
            if (amount == null) {
                totalAmount = donationMapper.getReceivedTotalAmount(MytxConfig.serviceUserId);//查询mysql方法
            } else {
                totalAmount = new BigDecimal(amount.toString());
            }
            result.put("totalAmount", totalAmount);

        }
        PageHelper.startPage(page, size);
        List<Donation> donations = donationMapper.queryReceivedDonations(MytxConfig.serviceUserId);
        PageInfo pageInfo = new PageInfo<>(donations);
        for (Donation donation : donations) {
            Boolean member = redisTemplate.opsForSet().isMember("DONATION_PRAISE_RECORD:" + donation.getId(), uId);
            donation.setHasPraise(member);
            Object praiseSize = redisTemplate.opsForValue().get("DONATION_PRAISE_SIZE:" + donation.getId());
            if (praiseSize != null) {
                donation.setPraiseSize((Integer) praiseSize);
            }
        }
        result.put("pageInfo", pageInfo);
        return CommonResult.ok(result);
    }

    /**
     * 根据主题id，查询出该主题收到的 捐赠记录
     *
     * @return
     */
    @PostMapping("/queryTopicDonations")
    public CommonResult queryTopicDonations(@RequestBody JSONObject body) {
        String uId = request.getHeader("uId");
        int page = 1;
        int size = 10;
        if (body.containsKey("page")) {
            page = (int) body.get("page");
        }
        if (body.containsKey("size")) {
            size = (int) body.get("size");
        }
        String topicId = body.getString("topicId");
        logger.info("queryTopicDonations:查询主题收到的捐赠记录:{}", topicId);


        PageHelper.startPage(page, size);
        List<Donation> donations = donationMapper.queryTopicDonationsOrderByAmount(topicId);
        PageInfo pageInfo = new PageInfo<>(donations);
        for (Donation donation : donations) {
            Boolean member = redisTemplate.opsForSet().isMember("DONATION_PRAISE_RECORD:" + donation.getId(), uId);
            donation.setHasPraise(member);
            Object praiseSize = redisTemplate.opsForValue().get("DONATION_PRAISE_SIZE:" + donation.getId());
            if (praiseSize != null) {
                donation.setPraiseSize((Integer) praiseSize);
            }
        }
        return CommonResult.ok(pageInfo);

    }


    @PostMapping("/donationPraise")
    public CommonResult donationPraise(@RequestBody String donationId) {
        String uId = request.getHeader("uId");
        redisTemplate.opsForValue().increment("DONATION_PRAISE_SIZE:" + donationId, 1);
        redisTemplate.opsForSet().add("DONATION_PRAISE_RECORD:" + donationId, uId);
        return CommonResult.ok();
    }

    @PostMapping("/removeDonationPraise")
    public CommonResult removeDonationPraise(@RequestBody String donationId) {
        String uId = request.getHeader("uId");
        redisTemplate.opsForValue().increment("DONATION_PRAISE_SIZE:" + donationId, -1);
        redisTemplate.opsForSet().remove("DONATION_PRAISE_RECORD:" + donationId, uId);
        return CommonResult.ok();
    }

    private User getServiceUser() {
        User serviceUser = null;
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(Constant.USER_SESSION + MytxConfig.serviceUserId);
        if (entries.size() != 0 && entries.containsKey("uId") && entries.containsKey("nick") && entries.containsKey("avatar")) {
            serviceUser = JSONObject.parseObject(JSONObject.toJSONString(entries), User.class);
        } else {
            serviceUser = userMapper.selectByPrimaryKey(MytxConfig.serviceUserId);
            redisTemplate.opsForHash().putAll(Constant.USER_SESSION + MytxConfig.serviceUserId, EntityUtils.objectToMap_v1(serviceUser));
            serviceUser.setPassword(null);
            serviceUser.setPayPassword(null);
            serviceUser.setPhone(null);
        }
        serviceUser.setuId(MytxConfig.serviceUserId);

        return serviceUser;
    }

    private User getUser(String uId) {
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(Constant.USER_SESSION + uId);
        if(entries.isEmpty()){
            return  userMapper.selectByPrimaryKey(uId);
        }
        return JSONObject.parseObject(JSONObject.toJSONString(entries), User.class);
    }


}
